/**
 * 食药公用js
 *
 * */
define([
    'base',
    'msgTool',
    'bootstrapDialog',
    'laydate',
    'bootstrapTable',
    'highcharts',
    'exporting',
    'highchartsCN',
    'sandSignika',
    'jqViewer',
    'jqPrint',
    'css!global/plugins/wangEditor/wangEditor.min.css',
    'plugins/wangEditor/wangEditor.min',
    'css!global/plugins/viewer/viewer.min.css',
    'plugins/fileInput/fileinput.min',
    'css!global/plugins/fileInput/fileinput.min.css',
], function (base, msgTool, BootstrapDialog, laydate, _, highcharts, _, _, _, _, jqPrint, _, E) {
    //默认加载基础库
    base();
    return {
        list: function (webUrl) {

            $.post('mainItemSelect.json', {},
                function (data) {
                    if (data.success) {
                        var selectHtml = "<option value=''>请选择</option>";
                        $.each(data.rows, function (i, itemMain) {
                            selectHtml += "<option value='" + itemMain.id + "'>" + itemMain.title + "</option>";
                        });
                        $("#mainSearch").html(selectHtml);
                    }
                }, "json");


            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: 'list.json'})
            };
            //table按需刷新动作
            var doAction = function (obj) {
                myTable.bootstrapTable('refresh', {url: 'list.json?pid=' + obj.id})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    window.location.href = row.id;
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '办件事项',
                        nameValue: row.title,
                        url: '../status/action'
                    })
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '办件事项',
                        nameValue: row.title,
                        url: '../delete/action'
                    });
                }
            };


            //table表格
            myTable.bootstrapTable({
                url: 'list.json', // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'id',
                        title: '事项编号',
                        align: 'center',
                        width: '5%'
                    }, {
                        field: 'title',
                        title: '办件主项名称',
                        width: '15%',
                        formatter: function (value, row, index) {
                            return '<i class="fa fa-hashtag text-primary" aria-hidden="true"></i>&emsp;<b>' + value
                        }
                    }, {
                        field: 'subTitle',
                        title: '办件子项名称',
                        width: '25%',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return "-";
                            }
                            return '<i class="fa fa-arrow-circle-o-right text-primary" aria-hidden="true"></i>&emsp;<b>' + value;
                        }
                    },{
                        field: 'mainItemTitle',
                        title: '所属部门',
                        align: 'center',
                        width: '10%'
                    }, {
                        field: 'legalTerm',
                        title: '法定期限',
                        width: '10%',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return "-";
                            }
                            return '<i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;' + value + '个工作日';
                        }
                    },
                    {
                        field: 'promiseTerm',
                        title: '承诺期限',
                        width: '10%',
                        formatter: function (value, row, index) {
                            if (value == null) {
                                return "-";
                            }
                            return '<i class="fa fa-clock-o" aria-hidden="true"></i>&nbsp;' + value + '个工作日'
                        }
                    },{
                        field: 'status',
                        title: '状态',
                        width: '10%',
                        align: 'center',
                        formatter: function (value, row, index) {
                            var result = "";
                            switch (value) {
                                case 0:
                                    result = "<span class=\"label label-danger\"><i class=\"fa fa-lock\" aria-hidden=\"false\"></i>&nbsp;禁用</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"label label-primary\"><i class=\"fa fa-unlock\" aria-hidden=\"true\"></i>&nbsp;启用</span>";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '20%',
                        formatter: operateFormatter,
                        events: operateEvents
                    }
                ]
            });

            //搜索刷新
            $('#search-btn').on('click', function () {
                tableRefresh();
            });


            //刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //批量修改状态
            $(".toolbar-batchStatus").on('click', function () {
                var entityList = myTable.bootstrapTable('getSelections');
                var row = [], names = [];
                $.each(entityList, function (i, v) {
                    names.push(v.itemName);
                    row.push(v.id);
                });
                if (row.length > 0) {
                    $.baseUtils.batchAction({
                        row: row,
                        tableName: myTable,
                        nameText: '食药申请',
                        nameValue: names,
                        url: '../status/batchAction'
                    });
                } else {
                    msgTool.error("请选择虽少一条记录后再操作", "信息提示");
                }

            });


            //搜索参数传递
            function queryParams(params) {
                params.search = $("#search").val();
                params.cateSearch = $("#cateSearch").val();
                params.mainSearch = $("#mainSearch").val();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    cateId: params.cateSearch,
                    mainId: params.mainSearch,
                    search: params.search//标题模糊搜
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }

        },
        view: function () {


        },

        save: function (cateId, mainId, officeTime) {

            // $("#picture").mouseover(function (e) {
            //     var imgUrl = $("#pictureVal").val();
            //     var x, y;
            //     x = e.clientX - 200 + 'px';
            //     y = e.clientY - 150 + 'px';
            //     $("#layer").css('left', x);
            //     $("#layer").css('top', y);
            //     $("#layer").html("<img  style='width: 200px;height: 200px;' src='http://127.0.0.1:8081/" + imgUrl + "'>");
            //     $("#layer").css("display", "");
            // });

            // $("#picture").mouseout(function () {
            //     $("#layer").html("");
            //     $("#layer").css('display', 'none');
            // });

            //工作时间
            laydate.render({
                elem: '#officeTime',
                type: 'time',
                format: 'H:mm',
                value: officeTime,
                range: true
            });

            $.post('cateSelect.json', {},
                function (data) {
                    if (data.success) {
                        var selectHtml = "<option value=''>请选择</option>";
                        $.each(data.rows, function (i, itemCate) {
                            var flag = "";
                            if (cateId == itemCate.id) {
                                flag = "selected";
                            }
                            selectHtml += "<option value='" + itemCate.id + "'  " + flag + " >" + itemCate.title + "</option>";
                        });
                        $("#cateId").html(selectHtml);
                    }
                }, "json");

            $.post('mainItemSelect.json', {'cateId': cateId},
                function (data) {
                    if (data.success) {
                        var selectHtml = "<option value=''>请选择</option>";
                        $.each(data.rows, function (i, itemMain) {
                            var flag = "";
                            if (mainId == itemMain.id) {
                                flag = "selected";
                            }
                            selectHtml += "<option value='" + itemMain.id + "'  " + flag + "   >" + itemMain.title + "</option>";
                        });
                        $("#mainId").html(selectHtml);
                    }
                }, "json");

            $("#cateId").change(function () {
                var param = $("#cateId option:selected").val();
                if (param == '') {
                    $("#mainId").html("<option value=''>请选择</option>");
                } else {
                    $.post('mainItemSelect.json', {'cateId': param},
                        function (data) {
                            if (data.success) {
                                var selectHtml = "<option value=''>请选择</option>";
                                $.each(data.rows, function (i, itemMain) {
                                    selectHtml += "<option value='" + itemMain.id + "'>" + itemMain.title + "</option>";
                                });
                                $("#mainId").html(selectHtml);
                            }
                        }, "json");
                }

            });


            $.baseUtils.uploader({
                filesType: 0,
                showCaption: false,
                browseLabel: "选择流程图...",
                uploadLabel: "上传",
                cssName: "#pictureUploader",
                browseClass: 'btn btn-primary',
                uploadClass: 'btn btn-info',
                errorCssName: "#error-message",
                fileExtensions: ['jpg', 'png', 'gif', 'jpeg'],
                //layoutTemplates: {actionUpload: ''}
            }).on("fileuploaded", function (event, data) {
                if (data.response !== null && data.response.status) {
                    $("#flowChart").val(data.response.domain + data.response.url);
                    $("#flowShow").find("img").attr("src", data.response.domain + data.response.url);
                } else {
                    msgTool.error(data.response.message, "信息提示");
                }
            });
            var length = 1;
            $("#addDepSteps").on("click", function () {
                var stepsCount = $("#depStepList").find("tbody tr").length;
                if (stepsCount > 0) {
                    length = stepsCount + 1;
                }
                $("#depStepList").find("tbody").append("<tr><td><textarea rows=\"3\" class=\"form-control\" name=\"depStepList[" + length + "].steps\" placeholder=\"例如：受理\"></textarea></td><td><textarea rows=\"3\" class=\"form-control\" name=\"depStepList[" + length + "].item\" placeholder=\"例如：按照《社会保障法》第八条进行审查\"></textarea></td><td><textarea rows=\"3\" class=\"form-control\" name=\"depStepList[" + length + "].office\" placeholder=\"例如：受理科\"></textarea></td><td><textarea rows=\"3\" class=\"form-control\" name=\"depStepList[" + length + "].promiseTerm\" placeholder=\"例如：当场办理\"></textarea></td><td><textarea rows=\"3\" class=\"form-control\" name=\"depStepList[" + length + "].legalTerm\" placeholder=\"例如：2天\"></textarea></td><td><button class=\"btn btn-danger btn-outline center-block\" onclick=\"$(this).parents('tr').remove()\">删除</button></td></tr>");
                length++;
            });


            $("#itemForm").validate({
                messages: { //自定义验证消息
                    title: {
                        required: "请输入主项名称"
                    },
                    subTitle: {
                        required: "请输入子项名称"
                    },
                    matterNature: {
                        required: "请输入事项性质"
                    },
                    mainId: {
                        required: "请选择所属部门"
                    },
                    basicCode: {
                        required: "请输入基本编码"
                    },
                    legalTerm: {
                        required: "请输入法定时限"
                    },
                    promiseTerm: {
                        required: "请输入承诺期限"
                    },
                    approvalUnit: {
                        required: "请输入审批主体"
                    },
                    address: {
                        required: "请输入办公地址"
                    },
                    phone: {
                        required: "请输入联系电话"
                    },
                    officeTime: {
                        required: "请输入办公时间"
                    },
                    link: {
                        required: "请输入事项链接"
                    },
                    basis: {
                        required: "请输入实施依据"
                    },
                    sort: {
                        required: "请输入事项排序"
                    },
                    cost: {
                        required: "请输入收费信息"
                    },
                    flowChart: {
                        required: "请点击上传效果图"
                    }
                }
            });

            //保存
            $('#doSubmit').on('click', function () {
                //是否下一步
                var existNext = $(this).data("exist-next");

                var valid = $("#itemForm").validate().form();
                if (valid) {
                    $.ajax({
                        url: '../save/action',
                        type: 'POST',
                        data: $('#itemForm').serialize(),
                        dataType: "JSON",
                        success: function (data) {
                            if (data.success) {
                                //如果下一步，就跳转
                                if (existNext) {
                                    window.location = "../view/" + parseInt(data.model) + "/filesList";
                                }
                                msgTool.success("保存成功！");
                            } else {
                                msgTool.error("保存失败！");
                            }
                        },
                        error: function () {
                            msgTool.error("操作失败，请刷新当前页面后重试！");
                        }
                    });
                }
            });


            /**
             * 富文本编辑器
             *
             */
            // createEditor("#guideEditer", "textarea[name='guide']");
            //
            // createEditor("#materialEditer", "textarea[name='material']");
            //
            //
            createEditor("#costEditer", "textarea[name='cost']");
            function createEditor(editor, deails) {
                var editor = new E(editor);
                var deails = $(deails);
                // 监控变化，同步更新到 textarea
                editor.customConfig.onchange = function (html) {
                    deails.text(html);
                };
                // 配置服务器端地址
                editor.customConfig.uploadImgServer = '/common/uploader/index';
                // 将图片大小限制为 30M
                editor.customConfig.uploadImgMaxSize = 30 * 1024 * 1024;
                // 限制一次最多上传 5 张图片
                editor.customConfig.uploadImgMaxLength = 50;
                // 上传文件名，类似于input>type=file>name
                editor.customConfig.uploadFileName = 'files';
                // 将 timeout 时间改为 20s
                editor.customConfig.uploadImgTimeout = 20000;
                // 自定义上传参数
                editor.customConfig.uploadImgParams = {
                    filesType: 2
                };
                editor.create();
            }

        },
        files: function () {

            var myTable = $('#dataList');
            var itemsId = myTable.data("items-id");
            var filesDomain = myTable.data("files-domain");
            var fileListUrl = '/itemsFiles/view/api/' + itemsId;
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: fileListUrl})
            };

            //table当前行的响应事件
            window.operateEvents = {
                'click .update': function (e, value, row) {
                    winModal("编辑", row);
                },
                'click .status': function (e, value, row) {
                    $.baseUtils.oneStatus({
                        row: row,
                        tableName: myTable,
                        nameText: '申请材料',
                        nameValue: row.fileName,
                        url: '/itemsFiles/status/action'
                    })
                },
                'click .delete': function (e, value, row) {
                    $.baseUtils.oneDelete({
                        row: row,
                        tableName: myTable,
                        nameText: '申请材料',
                        nameValue: row.fileName,
                        url: '/itemsFiles/delete/action'
                    });
                }
            };


            //table表格
            myTable.bootstrapTable({
                url: fileListUrl, // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                pageSize: 50,
                fixedColumns: true,//自动修复
                queryParams: function () {
                },//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                columns: [
                    {
                        field: 'id',
                        title: '编号',
                        align: 'center',
                        width: '5%'
                    }, {
                        field: 'fileName',
                        title: '文件名称',
                        width: '35%'
                    },
                    {
                        field: 'fileSize',
                        title: '文件大小',
                        align: 'center',
                        width: '10%'
                    }, {
                        field: 'sort',
                        title: '排序',
                        width: '10%',
                        align: 'center'
                    }, {
                        field: 'status',
                        title: '状态',
                        width: '10%',
                        align: 'center',
                        formatter: function (value) {
                            var result = "";
                            switch (value) {
                                case 0:
                                    result = "<span class=\"label label-danger\">&nbsp;禁用</span>";
                                    break;
                                case 1:
                                    result = "<span class=\"label label-primary\">&nbsp;启用</span>";
                                    break;
                                default:
                                    break;
                            }
                            return result;
                        }
                    }, {
                        field: 'action',
                        title: '操作',
                        align: 'center',
                        width: '30%',
                        formatter: function operateFormatter(value, row) {
                            var tempCode = "";
                            if (row.status === 1) {
                                tempCode += '<button type="button" class="status btn btn-default btn-white"><i class="fa fa-toggle-off"></i>&nbsp;禁用&nbsp;</button>';
                            } else {
                                tempCode += '<button type="button" class="status btn btn-default btn-white"><i class="fa fa-toggle-on"></i>&nbsp;启用&nbsp;</button>';
                            }
                            tempCode += '<button type="button" class="update btn btn-white">&nbsp;<i class="fa fa-edit"></i>&nbsp;修改&nbsp;</button>';
                            tempCode += '<button type="button" class="delete btn btn-white">&nbsp;<i class="fa fa-trash"></i>&nbsp;删除&nbsp;</button>';
                            return '<div class="btn-group btn-group-xs">' + tempCode + '</div>';
                        },
                        events: operateEvents
                    }
                ]
            });

            //工具栏 - 新增
            $('.toolbar-save').on('click', function () {
                winModal("新增", null);
            });

            //工具栏 - 刷新
            $(".toolbar-refresh").on('click', function () {
                tableRefresh();
            });

            //回显
            function responseHandler(res) {
                return res.rows;
            }

            //模态框
            function winModal(title, row) {
                BootstrapDialog.show({
                    type: BootstrapDialog.TYPE_DEFAULT,
                    tabindex: null,//解决select2搜索框失去焦点的问题
                    title: title,
                    closable: true,	//关闭箭头启动
                    closeByBackdrop: false,	//点击空白不消失
                    closeByKeyboard: true,//ESC取消禁用
                    message: $('<div></div>').load('/itemsFiles/save/form.html'),
                    data: {
                        'row': row
                    },
                    buttons: [{
                        label: '取消',
                        cssClass: 'btn-white cancel',
                        icon: 'fa fa-times',
                        action: function (dialog) {
                            dialog.close();
                        }
                    }, {
                        label: '提交' + title,
                        //hotkey: 13,//回车提交
                        cssClass: 'btn-primary',
                        icon: 'fa fa-check',
                        action: function (dialog) {
                            //返回验证结果
                            var flag = $("#winModal").validate().form();
                            if (flag) {
                                $.baseUtils.ajax({
                                    dialog: dialog,
                                    url: '/itemsFiles/save/action',
                                    data: $("#winModal").serialize(),
                                    text: "保存",
                                    isTable: true,
                                    tableName: '#dataList',
                                    isDialog: true
                                })
                            }
                        }
                    }],
                    onshown: function () {

                        /**
                         * 上传图片
                         */
                        $.baseUtils.uploader({
                            filesType: 1,
                            showCaption: false,
                            browseLabel: "选择事项文件",
                            uploadLabel: "上传",
                            cssName: "#filesUploader",
                            errorCssName: "#error-message",
                            fileExtensions: ['jpg', 'png', 'gif', 'jpeg', 'txt', 'zip', 'rar', '7z', 'doc', 'docx', 'xlsx', 'xls', 'pdf', 'ppt'],
                            layoutTemplates: {actionUpload: ''},
                        }).on("fileuploaded", function (event, data) {
                            if (data.response !== null && data.response.status) {
                                $("#url").val(data.response.url);
                                $("#fileName").val(data.response.originalName);
                                $("#fileSize").val(data.response.size);
                                $("#fileShow").html(
                                    "<div class='mt15'>" +
                                    "<a href=\"" + data.response.domain + data.response.url + "\" target=\"_blank\"><i class='fa fa-file'></i>&nbsp;" + data.response.originalName + "</a>" +
                                    "</div>");
                            } else {
                                msgTool.error(data.response.message, "信息提示");
                            }
                        });

                        $('#itemsId').val(itemsId);

                        if (row != null) {
                            $('#id').val(row.id);
                            $('#fileName').val(row.fileName);
                            $('#fileSize').val(row.fileSize);
                            $("#fileShow").html(
                                "<div class='mt15'>" +
                                "<a href=\"" + filesDomain + row.url + "\" target=\"_blank\"> <i class='fa fa-file'></i>&nbsp;" + row.fileName + "</a>" +
                                "</div>");
                            $('#url').val(row.url);
                            $('input[name=status][value=' + row.status + ']').attr('checked', true);
                            $('#sort').val(row.sort);
                        }
                    }
                });
            }


        }
    }
});






